package com.sservice.web.controller.pc;

import com.alibaba.fastjson.JSONObject;
import com.sservice.banfu.e.SaleInfo;
import com.sservice.banfu.e.Tpl;
import com.sservice.banfu.mapper.SaleInfoMapper;
import com.sservice.banfu.service.TplService;
import com.sservice.base.StringUtils;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.base.utils.image.PictureMerge;
import com.sservice.common.Constants;
import com.sservice.commonBusiness.e.Category;
import com.sservice.commonBusiness.e.DataR;
import com.sservice.commonBusiness.service.CategoryService;
import com.sservice.commonBusiness.service.DataRService;
import com.sservice.commonBusiness.service.FileService;
import com.sservice.commonBusiness.service.StatisticService;
import com.sservice.commonBusiness.type1.Category_TYPE;
import com.sservice.commonBusiness.vo.CategoryVo;
import com.sservice.commonBusiness.vo.FileVo;
import com.sservice.model.dao.IOfferDao;
import com.sservice.model.dao.OfferVarsMapper;
import com.sservice.model.entity.Offer;
import com.sservice.model.entity.UserWx;
import com.sservice.model.vo.OfferVo;
import com.sservice.service.service.*;
import com.sservice.urp.entity.User;
import com.sservice.web.wx.AdvancedUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

@Controller
@RequestMapping("/offer")
public class OfferPcController {
    @Autowired
    FileService fileService;
    @Autowired
    DataRService dataRService;
    @Autowired
    TplService tplService;
    @Autowired
    OfferVarsMapper offerVarsMapper;
    @Autowired
    ISaleLevelService iSaleLevelService;
    @Autowired
    SaleInfoMapper saleInfoMapper;
    @Autowired
    StatisticService statisticService;
    @Autowired
    private IOfferService offerService;
    @Autowired
    private IOfferDao offerDao;
    @Autowired
    private IUserService userService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private IUserWxService userWxService;
    @Autowired
    private Redis redis;

    /**
     * 同步shopify 数据
     *
     * @param url
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/shopify", method = RequestMethod.GET)
    public JSONObject pcAndTheme(String url) {
        return AdvancedUtil.httpsRequestWithUserAndPass("https://bytedevstore.myshopify.com/" + url,
                "GET", null, Constants.apikey, Constants.apiPs);
    }

    /**
     * 用户的分享卡片
     *
     * @return
     */
    @RequestMapping("/myQrCard")
    @ResponseBody
    public BaseResult myQrCard(String url, String title, HttpServletResponse response) throws IOException {
        BufferedImage destImg = PictureMerge.myQrCard(
                title != null ? title : "【只选对的】轻奢+潮牌外套5.5折",
                url != null ? url : "http://test1.ydlkeji.com/thumbnail/2018-10/1a5d7ba090154d3e909234f02ffa38b9_c.jpg",
                Constants.domain + "/admin/imgs/xcx/qr.png"
        );
        PictureMerge.saveImage(destImg, Constants.thumbnailPath + "/", "轻奢+潮牌外套5.5折.jpg", "jpg");
        return new BaseResult(true,
                Constants.nginxVisitUrl + "轻奢+潮牌外套5.5折.jpg",
                200);
    }

    /**
     * @param id       : 主题Id
     * @param skey
     * @param response
     * @throws IOException
     */
    @RequestMapping("/myThemeCard")
    @ResponseBody
    public BaseResult themeCard(String id, String skey, HttpServletResponse response) throws IOException {
        Category category = categoryService.selectByPrimaryKey(Integer.valueOf(id));

        BufferedImage destImg = PictureMerge.myQrCard(
                category.getName(),
                category.getUrl(),
                Constants.domain + "/admin/imgs/xcx/qr.png"
        );
        PictureMerge.saveImage(destImg, Constants.thumbnailPath + "/", category.getName() + ".jpg", "jpg");
        return new BaseResult(true,
                Constants.nginxVisitUrl + category.getName() + ".jpg",
                200);
    }

    /**
     * 品牌ID\分类ID\详情分享
     *
     * @param id
     * @param skey
     * @param response
     * @throws IOException
     */
    @RequestMapping("/myShareCard")
    @ResponseBody
    public BaseResult myShareCard(String id,
                                  String skey,
                                  String type,
                                  HttpServletResponse response) throws IOException {
        if ("detail".equals(type)) {
            Offer of = offerDao.selectByPrimaryKey(Integer.valueOf(id));
            BufferedImage destImg2 = PictureMerge.myShreCard(new String[]{
                            categoryService.selectByPrimaryKey(Integer.valueOf(of.getBrand())).getName()
                            , of.getName(), "¥" + of.getActualPrice()
                    },
                    Constants.domain + "/admin/imgs/xcx/img-panel.png",
                    Constants.domain + "/admin/imgs/xcx/logo-slogan.png",
                    of.getThumbnail(),
                    Constants.domain + "/admin/imgs/xcx/qr.png"
            );
            PictureMerge.saveImage(destImg2, Constants.thumbnailPath + "/", of.getName() + ".jpg", "jpg");
            return new BaseResult(true,
                    Constants.nginxVisitUrl + of.getName() + ".jpg",
                    200);
        }
        if ("brand".equals(type)) {
            Category brand = categoryService.selectByPrimaryKey(Integer.valueOf(id));
            BufferedImage destImg2 = PictureMerge.myShreCard(new String[]{
                    },
                    Constants.domain + "/admin/imgs/xcx/img-panel.png",
                    Constants.domain + "/admin/imgs/xcx/logo-slogan.png",
                    brand.getUrl(),
                    Constants.domain + "/admin/imgs/xcx/qr.png"
            );
            PictureMerge.saveImage(destImg2, Constants.thumbnailPath + "/", "share.jpg", "jpg");
            return new BaseResult(true,
                    Constants.nginxVisitUrl + "share.jpg",
                    200);
        }
        if ("category".equals(type)) {
            BufferedImage destImg2 = PictureMerge.myShreCard(new String[]{
                    },
                    Constants.domain + "/admin/imgs/xcx/img-panel.png",
                    Constants.domain + "/admin/imgs/xcx/logo-slogan.png",
                    Constants.domain + "/thumbnail/2018-10/1a5d7ba090154d3e909234f02ffa38b9_c.jpg",
                    Constants.domain + "/admin/imgs/xcx/qr.png"
            );

            PictureMerge.saveImage(destImg2, Constants.thumbnailPath + "/", "share.jpg", "jpg");
            return new BaseResult(true,
                    Constants.nginxVisitUrl + "share.jpg",
                    200);
        }

        return new BaseResult(false, "");


    }

    /**
     * 首页拼场和第一个拼场主题
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pcAndTheme", method = RequestMethod.GET)
    public BaseResult pcAndTheme(Offer arg) {
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setIsShow("1");
        categoryVo.setType1(Category_TYPE.TYPE_PC.getValue());//
        categoryVo.setSortOrder("DESC");
        categoryVo.setSortOrder("order_num");
        List<CategoryVo> service_res = categoryService.page(categoryVo);
        Map map = new HashMap();
        if (service_res.size() > 0) {
            categoryVo.setType1(Category_TYPE.TYPE_THEME.getValue());
            categoryVo.setDataRtype1("pc-theme");
            categoryVo.setSourceId(String.valueOf(service_res.get(0).getId())); //第一个拼场的主题
            List<CategoryVo> theme = categoryService.queryWithDrByPage(categoryVo);
            map.put("theme", theme);//
            map.put("page", new Pagination(1, categoryService.countWithDrByPage(categoryVo), 15));//
        }
        map.put("pc", service_res);
        BaseResult<Map> res = new BaseResult(true, map);
        return res;
    }

    /**
     * 商品品牌-按首字母顺序排序
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/brand", method = RequestMethod.GET)
    public BaseResult brand(Offer arg) {
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setSortOrder("order_num");
        categoryVo.setType1(Category_TYPE.TYPE_BRAND.getValue());//数据类型
        categoryVo.setSize(Integer.MAX_VALUE);
        List<CategoryVo> items = categoryService.queryByPage(categoryVo);
        char[] array = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        List list1 = new ArrayList();
        for (char item : array) { // 英文字母
            String itemA = String.valueOf(item).toUpperCase();//
            List<CategoryVo> list = items
                    .stream()
                    .filter(t -> t.getEn().substring(0, 1).toUpperCase().equals(itemA))
                    .sorted(comparing(CategoryVo::getEn))
                    .collect(Collectors.toList());
            if (list.size() != 0) {
                Map map = new HashMap();
                map.put("datas", list);
                map.put("header", itemA);
                list1.add(map);
            }
        }

        BaseResult<Map> res = new BaseResult(true, list1);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/shop-category", method = RequestMethod.GET)
    public BaseResult shopCateory(Offer arg) {
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setSortOrder("order_num");
        categoryVo.setType1(Category_TYPE.TYPE_SHOP_CATEGORY.getValue());//数据类型
        categoryVo.setSize(Integer.MAX_VALUE);
        List<CategoryVo> items = categoryService.queryByPage(categoryVo);
        List<CategoryVo> pList = items
                .stream()
                .filter(t -> t.getLevel().equals("1"))
                .sorted(comparing(CategoryVo::getOrderNum))
                .collect(Collectors.toList());
        List<CategoryVo> child = items
                .stream()
                .filter(t -> t.getLevel().equals("2"))
                .collect(Collectors.toList());
        for (CategoryVo item : pList) { // 英文字母
            List<CategoryVo> subList = child
                    .stream()
                    .filter(t -> item.getId().toString().equals(t.getpId()))
                    .sorted(comparing(CategoryVo::getOrderNum))
                    .collect(Collectors.toList());
            item.setList(subList);
        }

        BaseResult<Map> res = new BaseResult(true, pList);
        return res;
    }

    /**
     * 筛选条件
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/shop-filters", method = RequestMethod.GET)
    public BaseResult shopFilters(OfferVo arg) {
        BaseResult<Map> res = new BaseResult(true, offerService.getCategoryByRcecord(arg));
        return res;
    }

    /**
     * 查询某个主题下商品
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/shop-items", method = RequestMethod.GET)
    public BaseResult shop(OfferVo arg, String point, String skey) {
        boolean singleBrand = false;
        int brand = 0;
        if (StringUtils.isNoneBlank(arg.getColor())) {
            arg.setColor(toREGEXP(arg.getColor()));
        }
        if (StringUtils.isNoneBlank(arg.getSeason())) {
            arg.setSeason(toREGEXP(arg.getSeason()));
        }
        if (StringUtils.isNoneBlank(arg.getSizeId())) {
            arg.setSizeId(toREGEXP(arg.getSizeId()));
        }
        if (StringUtils.isNoneBlank(arg.getBrand())) {
            if (arg.getBrand().indexOf(",") == -1) {
                singleBrand = true;
                brand = Integer.valueOf(arg.getBrand());
                arg.setBrand(" = '" + brand + "' "); //--//
            } else {
                arg.setBrand(" in (" + arg.getBrand() + ") ");
            }
        }
        if (StringUtils.isNoneBlank(arg.getApplyGender())) {
            if (arg.getApplyGender().indexOf(",") == -1) {
                arg.setApplyGender(" = '" + arg.getApplyGender() + "' "); //--//
            } else {
                arg.setApplyGender(" in (" + arg.getApplyGender() + ") ");
            }
        }
        if (StringUtils.isNoneBlank(arg.getCategoryId())) {
            //arg.setCategoryId(toREGEXP(arg.getCategoryId()));
        }
        /**
         * 合同
         */
        if (StringUtils.isNoneBlank(arg.getDiscountId())) {
            if (arg.getDiscountId().indexOf(",") == -1) {
                arg.setDiscountId(" = '" + arg.getDiscountId() + "' "); //--//
            } else {
                arg.setDiscountId(" in (" + arg.getDiscountId() + ") ");
            }
        }
        if (StringUtils.isNoneBlank(arg.getDeliverPlace())) {
            if (arg.getDiscountId().indexOf(",") == -1) {
                arg.setDeliverPlace(" = '" + arg.getDeliverPlace() + "' "); //--//
            } else {
                arg.setDeliverPlace(" in (" + arg.getDeliverPlace() + ") ");
            }
        }
        if (StringUtils.isNoneBlank(arg.getApplyAge())) {
            arg.setApplyAge(toREGEXP(arg.getApplyAge()));
        }
        List<OfferVo> list = offerService.selectByTheme(arg);
        if ("fuli".equals(arg.getType1())) { //  福利

        }
        Map map = new HashMap();
        map.put("list", list);
        map.put("page", new Pagination(arg.getPage(), offerService.countByTheme(arg), arg.getSize()));

        if (singleBrand) {
            Category categoryVo = categoryService.selectByPrimaryKey(brand);
            map.put("extra", categoryVo);
        }
        if (StringUtils.isNoneBlank(skey)) {
            UserWx salep = userWxService.getLogined(skey); //
            SaleInfo saleInfo = new SaleInfo();//
            saleInfo.setSalePersonId(salep.getId() + "");//
//            SaleInfo si = saleInfoMapper.selectOne(saleInfo);//
//            Map map1 = iSaleLevelService.getLevel(Math.max(si.getCustomerCount(), si.getSalesCount()) + "");
//            map.put("level", map1);
        }

        return new BaseResult(true, map);
    }

    String toREGEXP(String str) {
        String colorStr = "";
        String[] colors = str.split(",");
        for (int i = 0; i < colors.length; i++) {
            colorStr += (i != 0 ? "|" : "") + "," + colors[i] + ",";
        }
        return colorStr;
    }

    /**
     * 创建
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Map> get(Offer arg, String skey) {
        OfferVo service_res = offerService.selectByPrimaryKey(arg.getId());
        User user = userService.selectByPrimaryKey(Integer.valueOf(service_res.getCreatorId()));
        Map map = new HashMap();
        if (service_res.getThemeId() == null) {
            DataR dataR = new DataR();
            dataR.setType1(Category_TYPE.TYPE_THEME_SHOP.getValue());//
            dataR.setTargetId(arg.getId());//  商品Id
            List<DataR> list = dataRService.selectBy(dataR);
            if (list.size() > 0 && list.get(0).getSourceId() != null) { //
                Category category = categoryService.selectByPrimaryKey(Integer.valueOf(list.get(0).getSourceId()));
                service_res.setThemeId(category.getId().toString());
                service_res.setThemeName(category.getName());
                service_res.setSiteFlag("1");
            }
        }
        //
        if (StringUtils.isNoneBlank(service_res.getDetail())) {
            Tpl tpl = tplService.selectById(Integer.valueOf(service_res.getDetail()));
            if (tpl == null) {
//                service_res.setDetail();
            } else {
                service_res.setDetail(new String(tpl.getContent()));
            }
        }
//        service_res.setRefundNotice("<p><strong>我该如何退回商品？</strong></p>\\r\\n<p>1.商品自签收之日起7日内(含第7日)，请保持商品吊牌包装完整，不经过洗涤。不影响二次销售，可享7天无理由退货；<br>\\r\\n2.商品自签收之日起7日内(含第7日)，因商品严重缺陷.发错货等非人为因素造成的商品残损，可享受有理由退货退款；<br><br>\\r\\n七天无理由退款，快递费用自行承担；有理由退货经核实后快递费用商家承担；<br><br>\\r\\n3.请特别留意，平台商品邮寄分国内顺丰邮寄与国际标准邮寄两种；如您所购买商品为国际标准邮寄，退货时需要邮寄至英国仓库，由此产生的费用，请您二次咨询客服。</p>\\r\\n<p><strong>我该如何更换商品？</strong></p>\\r\\n<p>非常抱歉，我们没有换货服务，如果需要调换尺码，您可以进行退货，再次重新购买合适的尺码。</p>\\r\\n<p>如果您有关于退换货或其他的问题可直接与我们的APP客服联系。</p>");
//        service_res.setDeliveryNotice("<p><strong>英国直邮</strong></p><p>EMS国际标准：时间：7-20个工作日  运费：包邮</p><p>EMS国际快捷：时间：3-7个工作日  运费：￥169</p><p><strong>国内发货</strong></p><p>顺丰快递：时间：1-3个工作日  运费：包邮</p><p>其它快递：时间：3-5个工作日  运费：包邮</p>");
        //service_res.setPo
        map.put("user", user);

        if (skey != null) {
            UserWx salep = userWxService.getLogined(skey); //
            if (salep != null) {
            }
            SaleInfo saleInfo = new SaleInfo();
            saleInfo.setSalePersonId(salep.getId() + "");
//            SaleInfo si = saleInfoMapper.selectOne(saleInfo);

        }
        map.put("offer", service_res);
        FileVo fileVo = new FileVo();
        fileVo.setDataRtype1("shop-banner");
        fileVo.setSourceId(service_res.getId().toString());
        // 商品详情
        map.put("files", fileService.selectByDataR(fileVo));//
        BaseResult<Map> res = new BaseResult(true, map);
        return res;
    }

    List getList(String ids) {
        String[] ids1 = ids.split(",");
        List<String> list = new ArrayList();
        for (String id : ids1) {
            list.add(id);
        }
        return list;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public BaseResult query(OfferVo arg) {
        List<OfferVo> list = offerService.queryByPagePC(arg);
        arg.setStatus("1");

        int total = offerService.queryCountPC(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        Map map = new HashMap();
        map.put("list", list);
        if (arg.getBrand() != null) { // 品牌ID
            map.put("brand", categoryService.selectByPrimaryKey(Integer.valueOf(arg.getBrand())));
        }
        map.put("page", page);
        return new BaseResult(true, map);
    }

    /**
     * 商品列表查询条件
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryInfoBy", method = RequestMethod.GET)
    public BaseResult queryInfoBy(CategoryVo arg) {
        Map map = new HashMap();
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setType1(Category_TYPE.TYPE_COLOR.getValue());
        categoryVo.setSize(Integer.MAX_VALUE);
        categoryVo.setCategoryId("1");
        //颜色
        List list = categoryService.queryByPage(categoryVo);
        map.put("color", list);
        //季节
        List season = categoryService.queryByPage(categoryVo);
        map.put("season", season);

        //品牌
        List brand = categoryService.queryByPage(categoryVo);
        map.put("brand", brand);

        //尺码
        List sizes = categoryService.queryByPage(categoryVo);
        map.put("sizes", sizes);

        //尺码
        List category = categoryService.queryByPage(categoryVo);
        map.put("category", category);

        //仓库
        List warehouse = categoryService.queryByPage(categoryVo);
        map.put("warehouse", warehouse);


        //
        List attr = categoryService.queryByPage(categoryVo);
        map.put("attr", attr);

        //
        List value = categoryService.queryByPage(categoryVo);
        map.put("value", value);

        return new BaseResult(true, map);
    }

    /**
     * 查找最新3个报价
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryLatest", method = RequestMethod.GET)
    public ListResult<OfferVo> queryLatest(OfferVo arg) {
        List<OfferVo> list = offerService.queryByPagePC(arg);
        arg.setStatus("1");
        int total = offerService.queryCountPC(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<OfferVo> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    /**
     * 我的关注/ 收藏
     *
     * @param arg
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/focus", method = RequestMethod.GET)
    public ListResult focus(OfferVo arg, String skey, HttpSession session) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);

        if (salep == null) {
            return new ListResult(false, "请登录!", 401);
        }
        arg.setUserId(String.valueOf(salep.getId()));
        List<OfferVo> list = offerService.queryByPagePCFocus(arg);
        arg.setStatus("1");
        int total = offerService.queryCountPCFocus(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<OfferVo> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/focus-count", method = RequestMethod.GET)
    public BaseResult focusCount(OfferVo arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new ListResult(false, "请登录!", 401);
        }
        arg.setUserId(String.valueOf(salep.getId()));
        arg.setStatus("1");
        int total = offerService.queryCountPCFocus(arg);
        BaseResult res = new BaseResult(true, total);
        return res;
    }

    /**
     * 种植植物
     *
     * @param arg
     * @param skey
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryCommonByDr", method = RequestMethod.GET)
    public BaseResult queryCommonByDr(OfferVo arg, String skey) {
        List<OfferVo> list = offerService.queryCommonByDr(arg);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(arg.getPage(), offerService.countCommonByDr(arg), arg.getSize()));
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryPlain", method = RequestMethod.GET)
    public ListResult queryPlain(OfferVo arg, String skey) {
        List<OfferVo> list = offerService.queryByPage(arg);
        int total = offerService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }


}
